<template>
  <div class="container">
    <!-- 左侧导航栏 -->
    <div class="sidebar">
      <ul>
        <li
          v-for="item in navItems"
          :key="item.id"
          @click="selectItem(item)"
          :class="{ active: selectedItem.id === item.id }"
        >
          {{ item.title }}
        </li>
      </ul>
    </div>

    <!-- 右侧内容展示区域 -->
    <div class="content">
      <h1>{{ selectedItem.title }}</h1>

      <!-- 动态生成表单或展示区域 -->
      <div v-for="(field, index) in selectedItem.fields" :key="index" class="field-group">
        <!-- 文本/直接展示输入框 -->
        <div v-if="field.type === 'text' || field.type === 'number' || field.type === 'date'" class="form-group">
          <label :for="field.key">{{ field.label }}:</label>
          <input
            v-if="field.editable"
            :type="field.type"
            :id="field.key"
            v-model="middle_userinfo[field.key]"
            :placeholder="field.placeholder || '请输入'"
            @mouseover="showButton($event, field)"
            @mouseout="hideButton($event, field)"
            class="input_text"
          />
          <div v-if="!field.editable" style="margin-left: 8px; font-size: 16px;">
            {{ field.value }}
          </div>
        </div>

        <!-- 选择框 -->
        <div v-if="field.type === 'select'" class="form-group">
          <label :for="field.key">{{ field.label }}:</label>
          <select
            :id="field.key"
            v-model="middle_userinfo[field.key]"
            class="custom-select"
          >
            <option v-for="option in field.options" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
        </div>

        <!-- 静态数据 -->
        <div v-if="field.type === 'static'" class="form-group">
          <span class="static-data"> {{ field.label }}: {{ field.value }} </span>
        </div>

        <!-- 不可直接展示 -->
        <div v-if="field.type === 'noneshow'" class="form-group">
          <span class="noneshow_span_l">{{ field.label  }} <span v-if="field.value">：</span>{{ field.value }}</span>
          <div style="display: inline-block;" v-for="i in field.func" :key="i.name">
            <span class="noneshow_span_r" @click="i.click">{{ i.name }}</span>
          </div>
        </div>
        

        <!-- 文件类 -->
        <div v-if="field.type === 'file'" class="form-group">
          <div style="display: inline-block;">
              <span class="noneshow_span_l">{{ field.label  }}</span>
              <span class="noneshow_span_r" @click="up_single_file(field.limits, field.key)">{{'上传'}}</span>
              <span class="noneshow_span_r" v-if="middle_userinfo[field.key]" @click="render_single_file(field.key)" >
                预览
              </span>
              
          </div>
        </div>
      </div>
      

      <button v-if="selectedItem.submit" @click="selectedItem.submit()" class="save-button">提交</button>
    </div>
  </div>
  <Cover :show_cover="show_cover"/>
  <AlertTable   @close_formdata="close_alert_formdata"  v-if="show_alert_table" style="position: fixed; top:100px "    :fields="current_alert_tabel.fields"  :sections="current_alert_tabel.sections"  />
</template>

<script setup>
// 目前信息的处理暂且设置为会话级别不做直接显示处理
import { onMounted, ref ,reactive,inject} from 'vue';
import { resetac,get_VerificationCode, judge_VerificationCode } from '@/api/user';
import AlertTable from "@/components/common/formdata3.vue"
import Cover from "@/components/common/cover.vue"
import { warning,success } from '@/static/js/alert';
let show_alert_table = ref(false)
let show_cover = ref(false)
let user_store = inject('user')()
let user_info=reactive(user_store.value.get_user())
let middle_userinfo = reactive({
  'id': user_info.id,
  'account': user_info.account,
  'name': user_info.name || '未设置',
  'username': user_info.username || '未设置',
  'age': user_info.age || 1,
  'sex': user_info.sex || '保密', // 确保有默认值
  'email': user_info.email || '未设置',
  'phone': user_info.phone || '未设置',
  'password': user_info.password ,
  'introduction': user_info.introduction || '这个人很懒，什么都没有留下',
  'admin': undefined,
  'head_image': user_info.head_image,
  'address': user_info.address,
  'app_index_image': user_info.app_index_image,
});


// 导航栏数据
const navItems = ref([
{
    id: 1,
    title: '个人信息',
    submit: () => { resetac(middle_userinfo)},
    fields: [
      { key: 'name', label: '姓名', type: 'text', value: user_info.name, placeholder: '请输入姓名', editable: true, showeditor: false, },
      { key: 'username', label: '昵称', type: 'text', value: user_info.username, placeholder: '请输入昵称', editable: true, showeditor: true, },
      { key: 'age', label: '年龄', type: 'number', value: user_info.age, placeholder: '请输入年龄', editable: true, showeditor: true, },
      {
        key: 'sex', label: '性别', type: 'select',
        options: [
          { value: '保密', label: '保密' },
          { value: '男', label: '男' },
          { value: '女', label: '女' }
        ],
        value: user_info.sex || '00', // 确保有默认值
        placeholder: '性别', editable: true, showeditor: true,
      },
      { key: 'email', label: '邮箱', type: 'text', value: user_info.email, placeholder: '请输入邮箱', editable: true, showeditor: false, }
      ,
       { key: 'introduction', label: '简介', type: 'text', value: user_info.name, placeholder: '请输入简介', editable: true, showeditor: false, },
    ],
  },
  {
    id: 2,
    title: '账号信息',
    fields: [
      {
        key: 'uid', label: 'id', type: 'static', value: user_info.id,
        editable: false, showeditor: false, func: []
      },
      {
        key: 'password', label: '密码状态', type: 'noneshow', value: '', placeholder: '',
        editable: true, showeditor: false,
        func: [{
          "name": "修改", "click": function (event) {
              render_alert_table(event, 'fix_ps')
          }
        }],
      },
      {
        key: "phone", label: "手机号", type: "noneshow", value: user_info.phone, placeholder: "",
        editable: false, showeditor: false, func: [{ "name": "修改" ,"click": function (event) {
             render_alert_table(event, 'phone') 
        }
        }],
      }, {
        key: "head_image", label: "头像", type: "file",
        limits: { accept: ['image/jpeg', 'image/png'] },
        value: user_info.head_image,
        placeholder: "",
        editable: false, showeditor: false, 
      },{
        key: "app_index_image", label: "首页图片", type: "file",
        limits: { accept: ['image/jpeg', 'image/png'] },
        value: user_info.app_index_image,
        placeholder: "",
        editable: false, showeditor: false, 
      }
    ]
  }
]);


// 当前选中的导航项
const selectedItem = ref(navItems.value[0]);

// 选择导航项的方法
const selectItem = (item) => {
  selectedItem.value = item;
};

const up_single_file = (limits, key) => { 
  // 单文件上传处理方案
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = limits.accept || 'image/*'; 
  input.onchange = (event) => {
    const file = event.target.files[0];
    // 验证文件大小 (16MB = 16 * 1024 * 1024 bytes)
    const MAX_SIZE = 16 * 1024 * 1024;
    if (file.size > MAX_SIZE) {
      alert('文件大小不能超过16MB');
      return;
    }
    const reader = new FileReader();
    reader.onload = (e) => {
      middle_userinfo[key] = e.target.result;
      resetac(middle_userinfo)
      user_store.value.set_user_info(middle_userinfo)
    };
    reader.onerror = () => {
      alert('文件读取失败');
    };
    
    reader.readAsDataURL(file);
  };
  
  input.click();
};
const render_single_file = (key) => {
  const overlay = document.createElement('div');
  overlay.style.position = 'fixed';
  overlay.style.top = '0';
  overlay.style.left = '0';
  overlay.style.width = '100%';
  overlay.style.height = '100%';
  overlay.style.backgroundColor = 'rgba(0,0,0,0.5)';
  overlay.style.zIndex = '9998';
  overlay.style.cursor = 'pointer';

  const updae_image = document.createElement('img');
  updae_image.src = middle_userinfo[key];
  updae_image.style.width = '500px';
  updae_image.style.height = 'auto';
  updae_image.style.objectFit = 'cover';
  updae_image.style.position = 'fixed';
  updae_image.style.top = '50%';
  updae_image.style.left = '50%';
  updae_image.style.transform = 'translate(-50%, -50%)';
  updae_image.style.zIndex = '9999';
  updae_image.style.border = '1px solid #ccc';
  updae_image.style.borderRadius = '5px';
  updae_image.style.pointerEvents = 'none'; // 关键设置：允许点击穿透

  //移除函数
  const removeElements = () => {
    document.body.removeChild(overlay);
    document.body.removeChild(updae_image);
    overlay.removeEventListener('click', removeElements); // 移除监听
  };


  overlay.addEventListener('click', removeElements);


  document.body.appendChild(overlay);
  document.body.appendChild(updae_image);
};



// 保存修改的方法
const saveChanges = () => {
  alert('修改已保存：' + JSON.stringify(selectedItem.value, null, 2));
};

// 鼠标悬浮时显示编辑按钮
const showButton = function (event, field) {
  if (field.editable) {
    event.target.setAttribute('editable', true);
  }
};

// 鼠标移出时隐藏编辑按钮
const hideButton = function (event, field) {
  if (field.editable) {
    event.target.setAttribute('editable', false);
  }
};


// 弹窗信息
let alerttable =reactive({
   fix_ps: {
    sections: ['修改密码']
    ,
    fields:[
      {
        title: '修改密码',
        step: true, // 需要分步
        steps: [
          {
            step: 1,
            fields: [
              { id: 'email', label: '邮箱', type: 'email', placeholder: '请输入注册邮箱', autocomplete: 'off' },
            ],
            func: async (value) => {
              if (value.email == '') {
                warning("请输入完整信息!")
                return false
              }

              const VerificationCode = await get_VerificationCode(value.email, user_store.value.get_user().account)
              if (VerificationCode) {
                const data = JSON.stringify({
                  VerificationCode,
                  date: Date.now(),
                })
                localStorage.setItem('VerificationCode', data)
                return true
              } else {
                return false
              }
            }

          },
          {
            step: 2,
            fields: [
              { id: 'verificationCode', label: '验证码', type: 'text', placeholder: '请输入验证码', autocomplete: 'off' },
            ],
            func:async  (value) => {
              if (value.verificationCode == "") {
                warning("请输入完整信息!")
                return false
              }
              if (value.verificationCode) {
                // 进行判断
                const id = JSON.parse(localStorage.getItem('VerificationCode')).VerificationCode.id;
                const timestamp = JSON.parse(localStorage.getItem('VerificationCode')).VerificationCode.date;
                const currentTimestamp = Date.now();
                const fiveMinutesInMilliseconds = 5 * 60 * 1000;
                const isExpired = currentTimestamp - timestamp > fiveMinutesInMilliseconds;
                if (isExpired) {
                  // 时间戳过了5min失效
                  warning("验证码已失效,请重新获取")
                  return false
                } else {
                  const judge = await judge_VerificationCode(id, value.verificationCode)
                  if (judge == 1) {
                    success('验证码正确')
                    return true
                  } else {
                    warning('验证码错误')
                    return false
                  }
                }
              }
            }
          
          },
          {
            step: 3,
            fields: [
              { id: 'newPassword', label: '新密码', type: 'password', placeholder: '请输入新密码', autocomplete: 'off' },
              { id: 'confirmNewPassword', label: '确认新密码', type: 'password', placeholder: '请再次输入新密码', autocomplete: 'off' },
            ],
            func:async  (value) => {
              if (value.newPassword == '' || value.confirmNewPassword == '') { 
                warning("请输入完整信息!")
                return false
              }
              if (value.newPassword != value.confirmNewPassword) {
                warning("两次密码不一致!")
                return false
              }
              const judge = await resetac({ account: user_store.value.get_user().account, password: value.newPassword })
              if (judge == 1) {
                 success('修改成功!' +
                '\n' + "您的新密码是:" + value.password,5000);
                return true
              } else {
                warning('修改失败!')
                return false
              }
            }
          },
        ],
        step_model: {
          current: 1,
          All_Steps: 3,
        },
      },
    ]
  },
  phone: {
    sections: ['手机号'],
    fields: [
      {
        title: '手机号',
        step: false, // 不需要分步
        fields: [{ id: 'phone', label: '手机号', type: 'text', placeholder: '请输入手机号', autocomplete: 'off' }],
        func: async (value) => { 
          // 由于目前对手机号没有拓展只有标记位,所以直接修改即可
         const judge = await resetac({ account: user_store.value.get_user().account, phone: value.phone })
              if (judge == 1) {
                success('修改成功!')
                // 此处可优化将navitem设置为computed处理[实际是user_info获取的仓库数据]
                // (因为我们用的是user_info但是双向绑定的是middle_userinfo)
                middle_userinfo.phone = value.phone
                 user_store.value.set_user_info_by_key("phone",value.phone)
                return true
              } else {
                warning('修改失败!')
                return false
              }
        }
      }]
  }   
})

let current_alert_tabel = ref({
  fileds: [],
  sections: []
})
// 渲染弹窗
const render_alert_table = (event, section) => {
    const true_Section = String(section)
    current_alert_tabel.value = alerttable[true_Section]
    show_cover.value = true
    show_alert_table.value = true
   
}
// 关闭弹窗
const close_alert_formdata = function () {
  show_alert_table.value = false
  show_cover.value=false
}






onMounted(async () => { 
 
})
</script>

<style scoped>
.container {
  display: flex;
  height: calc(100vh - 40px);
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  box-sizing: border-box;
}
/* 左侧导航 */
.sidebar {
  width: 200px;
  background-color: #2c3e50;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.sidebar ul {
  list-style: none;
  padding: 0;
}

.sidebar li {
  padding: 10px;
  cursor: pointer;
  color: #ffffff;
  transition: background-color 0.3s;
  border-radius: 4px;
}

.sidebar li:hover {
  background-color: #34495e;
}

.sidebar li.active {
  background-color: #1abc9c;
  color: white;
}
/* 右侧盒子 */
.content {
  flex: 1;
  margin-left: 20px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h1 {
  margin-top: 0;
  color: #2c3e50;
}



/* 右侧标题组 */
.field-group {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
  width: 800px;
  /* background-color: black; */
}

label {
  display: block;
  margin-bottom: 5px;
  color: #34495e;
  font-size: 18px;
}
/* 可修改 */
.input_text{
  padding-left: 8px;
  border: none;
  font-size: 16px;

}

/* 右侧noneshow */
.noneshow_span_l{
  display: inline-block;
  width: 400px;
  margin-right: 150px;
  font-size: 18px;
  /* background-color: black; */
}
.noneshow_span_r{
  padding: 10px 20px;
  background-color: #808695;
  color: white;
  border: none;
  border-radius: 80px;
  cursor: pointer;
  margin-right: 5px;
  transition: background-color 0.3s;
}
.noneshow_span_r:hover{
  background-color: #515a6e;
}
/* 选择 */
.custom-select{
    margin-left: 8px;
    width:50px;
    text-align:center;
    line-height: 16px;
    padding: 2px;
    font-size: 16px;
    border: 2px solid #ccc;
    border-radius: 4px;
    background-color: #fff;
    color: #333;
    appearance: none;
    cursor: pointer;
    background-repeat: no-repeat;
    background-position: right 10px center;
    background-size: 10px;
}

/* 静态数据 */
.static-data{
  display: inline-block;
  width: 400px;
  font-size: 18px;
}

.save-button {
  padding: 10px 20px;
  background-color: #1abc9c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.save-button:hover {
  background-color: #16a085;
}
</style>

